package main

import (
	"fmt"
	"image"
	"image/png"
	"io/ioutil"
	"net/http"
	"os"
	"rgones/nes"
	"rgones/nes/render"
	"strconv"
)

func saveScreenState(frame []uint8, pngName string) {
	img := image.NewRGBA(image.Rect(0, 0, 256, 240))
	for i := 0; i < 256*240; i++ {
		img.Pix[i*4] = frame[i*3]
		img.Pix[i*4+1] = frame[i*3+1]
		img.Pix[i*4+2] = frame[i*3+2]
		img.Pix[i*4+3] = 0xff
	}
	pngRes := "../pngs/" + pngName + ".png"

	fmt.Println("saving to", pngRes)

	f, _ := os.Create(pngRes)
	defer f.Close()

	err := png.Encode(f, img)
	if err != nil {
		fmt.Println(err, "png encode error")
		return
	}
}
func RunApp(romBytes []byte) {
	// 运行再一个进程中
	var screenUpdateNum = 0

	//读取rom文件
	rom, _ := nes.NewRom(romBytes)
	frame := render.NewFrame()

	

	bus := nes.NewBus(rom, func(ppu *nes.NesPPU) {
		nes.Render(ppu, frame)
		saveScreenState(frame.Data, strconv.Itoa(screenUpdateNum))
		screenUpdateNum++
	})

	cpu := nes.NewCpu(bus)

	cpu.Reset()


	cpu.Run_with_callback(func(ref_cpu *nes.CPU) {
	
	})
}

func loadFileFromUrl() []byte {
	url := "http://localhost:63342/rgones/html/nestest.nes"

	// 发起GET请求
	resp, err := http.Get(url)
	if err != nil {
		// 处理错误
		panic(err)
	}

	// 确保在函数退出前关闭响应体
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// 处理错误
		panic(err)
	}
	return body
}

func loadRomByNet() {
	body := loadFileFromUrl()
	RunApp(body)
}

func loadRomByLocal() {
	// 从本地加载ROM
	romBytes, err := ioutil.ReadFile("./rom/wrecking.nes")
	println(romBytes)
	if err != nil {
		fmt.Println("read file error")
		panic(err)
	} else {
		RunApp(romBytes)
	}
}

func main() {
	loadRomByLocal()
}
